﻿using PageAdmin.Utils.ORM;
using System;
using System.Collections.Generic;
namespace PageAdmin.Utils.BLL
{
    /// <summary>
    /// 更新字段值接口
    /// </summary>
    public class SetFieldBLL : ISetField
    {
        public HashSet<string> CanSetFieldList { get; set; }

        /// <summary>
        /// 执行前的委托
        /// </summary>
        public Func<TipsInfo> Executing { get; set; }

        /// <summary>
        /// 数据库对象
        /// </summary>
        private DataBaseContext _DbContext;

        public SetFieldBLL(DataBaseContext dataBaseContext)
        {
            _DbContext = dataBaseContext;
            CanSetFieldList = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        }
        /// <summary>
        /// 限制可设置的字段，避免伪造
        /// </summary>
        private void validateField(string setField, TipsInfo tipsInfo)
        {
            if (setField == null || !CanSetFieldList.Contains(setField))
            {
                tipsInfo.State = 0;
                tipsInfo.Msg = "未设置setField字段，或未被允许设置此字段";
            }
        }

        /// <summary>
        /// 根据实体更新字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tModelList"></param>
        /// <param name="setField"></param>
        /// <returns></returns>
        public TipsInfo SetListField<T>(string setField,dynamic setValue, IEnumerable<int> idList) where T : class, new()
        {
            TipsInfo tipsInfo = new TipsInfo();
            //validateField(setField, tipsInfo);
            if (Executing != null)
            {
                tipsInfo = Executing.Invoke();
            }
            if (tipsInfo.State == 0)
            {
                return tipsInfo;
            }
            try
            {
                foreach (int id in idList)
                {
                    _DbContext.AddDbParamter("Id", id);
                    _DbContext.DbSet<T>().Update(setField, setValue, "[Id]=@Id");
                }
            }
            catch (Exception e)
            {
                tipsInfo.State = 0;
                tipsInfo.Msg = e.Message;
            }
            return tipsInfo;
        }


    }
}